package com.ldb.Controller.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;

import com.ldb.Controller.entity.Student;

//@Lazy(true)
//@Transactional
public class BaseDao<T> implements IBaseDao<T> {
	
	protected SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public BaseDao() {}
	
	/** clazz中存储了当前操作的类型，即泛型T */
    private Class<?> clazz;
    
    public BaseDao(Class<?> clazz) {
        this.clazz = clazz;
    }
    
    public void setClazz(Class<?> clazz) {
    		this.clazz = clazz;
    }

	@Override
	public void addEntity(T entity) {
		Session session = this.sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		session.save(entity);
		tx.commit();
	}

	@Override
	public boolean deleteEntity(Class<?> T,String id) {
		System.out.println(T);
		Session session = this.sessionFactory.openSession();
		session.load(T, id);
        Transaction tx = session.beginTransaction();
        session.delete(session.load(T, id));
        tx.commit();
        return true;
	}

	@Override
	public boolean updateEntity(String id,T entity) {
		Session session = this.sessionFactory.openSession();
		session.load(entity.getClass(), id);
        Transaction tx = session.beginTransaction();
        session.update(entity);
        tx.commit();
		return true;
	}

	@Override
	public T getEntity(String str) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public T getEntity(String keyId,String id,Class<?> T) {
		T t = (T) this.sessionFactory.getCurrentSession().load(T, id);
		return t;
	}

	@Override
	public List<T> getEntityAll() {
		String hql = "from "+this.clazz.getSimpleName();
		List<T> result = this.sessionFactory.getCurrentSession().createQuery(hql).list();
		return  result;
	}
	
	public List<T> getEntityAllDesc(){
		String hql = "from "+this.clazz.getSimpleName()+" order by timeStamp Desc";
		List<T> result = this.sessionFactory.getCurrentSession().createQuery(hql).list();
		return  result;
	}

	@Override
	public List<T> getEntityList(String key,String value) {
		String hql = "from "+this.clazz.getSimpleName()+" as t where t."+key+" = "+"'"+value+"'";
		List<T> result = this.sessionFactory.getCurrentSession().createQuery(hql).list();
		return  result;
	}
	
	/*
	 * 模糊查询
	 */
	public List<T> getEntityListNotSure(String key,String value) {
		String hql = "from "+this.clazz.getSimpleName()+" as t where t."+key+" like :title";
		List<T> result = this.sessionFactory.getCurrentSession().createQuery(hql).setString("title", "%"+value+"%").list();
		return  result;
	}
	
	
	/**
     * <HQL分页查询>
     *
     * @param hql
     * @param countHql 查询记录条数的HQL语句
     * @param pageNo   下一页
     * @param pageSize 一页总条数
     * @param values
     * @return
     */
    public PageResults<T> findPageByFetchedHql(int pageNo, int pageSize, Object... values) {
        PageResults<T> retValue = new PageResults<T>();
        Session session = this.sessionFactory.getCurrentSession();
        Query query = session.createQuery("from "+this.clazz.getSimpleName());
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        int currentPage = pageNo > 1 ? pageNo : 1;
        retValue.setCurrentPage(currentPage);
        retValue.setPageSize(pageSize);
        ScrollableResults results = query.scroll();
		results.last();
		retValue.setTotalCount(results.getRowNumber() + 1);// 设置总记录数
        retValue.resetPageNo();
        List<T> itemList = query.setFirstResult((currentPage - 1) * pageSize).setMaxResults(pageSize).list();
        if (itemList == null) {
            itemList = new ArrayList<T>();
        }
        retValue.setResults(itemList);
        return retValue;
    }
    
    /**
     * <根据HQL得到记录数>
     *
     * @param hql
     * @param values
     * @return
     */
    public Long countByHql(String hql, Object... values) {
        Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        return (Long) query.uniqueResult();
    }

}
